import React, { createContext, useContext, useState, useEffect } from 'react';
import { message } from 'antd';

const AuthContext = createContext();

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [token, setToken] = useState(localStorage.getItem('token'));

  // 检查用户是否已登录
  const isAuthenticated = () => {
    return !!token && !!user;
  };

  // 登录
  const login = async (credentials) => {
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(credentials),
      });

      const data = await response.json();

      if (data.code === 200) {
        const { token: newToken, user: userData } = data.data;
        setToken(newToken);
        setUser(userData);
        localStorage.setItem('token', newToken);
        localStorage.setItem('user', JSON.stringify(userData));
        message.success('登录成功');
        return { success: true };
      } else {
        message.error(data.message || '登录失败');
        return { success: false, message: data.message };
      }
    } catch (error) {
      console.error('登录错误:', error);
      message.error('登录失败，请检查网络连接');
      return { success: false, message: '网络错误' };
    }
  };

  // 注册
  const register = async (userData) => {
    try {
      const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(userData),
      });

      const data = await response.json();

      if (data.code === 200) {
        const { token: newToken, user: userInfo } = data.data;
        setToken(newToken);
        setUser(userInfo);
        localStorage.setItem('token', newToken);
        localStorage.setItem('user', JSON.stringify(userInfo));
        message.success('注册成功');
        return { success: true };
      } else {
        message.error(data.message || '注册失败');
        return { success: false, message: data.message };
      }
    } catch (error) {
      console.error('注册错误:', error);
      message.error('注册失败，请检查网络连接');
      return { success: false, message: '网络错误' };
    }
  };

  // 登出
  const logout = () => {
    setToken(null);
    setUser(null);
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    message.success('已退出登录');
  };

  // 更新用户信息
  const updateUser = (userData) => {
    setUser(userData);
    localStorage.setItem('user', JSON.stringify(userData));
  };

  // 验证token有效性
  const validateToken = async () => {
    if (!token) {
      setLoading(false);
      return;
    }

    try {
      const response = await fetch('/api/auth/refresh-token', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      });

      const data = await response.json();

      if (data.code === 200) {
        // Token有效，更新token
        const newToken = data.data.token;
        setToken(newToken);
        localStorage.setItem('token', newToken);
        
        // 如果没有用户信息，从localStorage获取
        if (!user) {
          const savedUser = localStorage.getItem('user');
          if (savedUser) {
            setUser(JSON.parse(savedUser));
          }
        }
      } else {
        // Token无效，清除认证信息
        logout();
      }
    } catch (error) {
      console.error('Token验证错误:', error);
      logout();
    } finally {
      setLoading(false);
    }
  };

  // 初始化时验证token
  useEffect(() => {
    validateToken();
  }, []);

  const value = {
    user,
    token,
    loading,
    isAuthenticated,
    login,
    register,
    logout,
    updateUser,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}; 